var equipmentStatusData = {};
var time = undefined;
var deviceState = undefined;
var chargingGun = undefined;
var socStatusChart = undefined;
var countData = [];
var outputVoltageData = [];
var outputElectricData = [];
var currentSOCData = [];
var startEchart = false;
var chargingChart = undefined;

$(document).ready(function() {
	showLoading();
	$('title', parent.document).html($('title').text());
	setBaseUrl();
	addTitle("equipmentStatusDetails");
	search();
	initSocStatusChart();
	$("#histogram").empty();
	chargingChart = echarts.init(document.getElementById('histogram'));
	chargingChart.showLoading({text : "曲线加载中..."});
	$ajax('realTimeCharging', {ChargingStationID:$("#chargingStationID", parent.document).val(), EquipmentNo: $("#detailID", parent.document).val(), chargingType: "EQUIPMENT"}, searchChargingStatus, '', searchChargingStatus);
	setTimeout(hideLoading, 1500);
})
function search(){
	$ajax('realTimeEquipmentDetail', {EquipmentNo: $("#detailID", parent.document).val()}, searchEquipmentStatus, '', searchEquipmentStatus);
}
function searchChargingStatus(data){
	if(data && data.outputVoltage && data.outputVoltage.length > 0){
		var length = outputVoltageData.length;
		var tempOutputVoltageData = data.outputVoltage || [];
		var tempOutputElectricData = data.outputElectric || [];
		var tempCurrentSOCData = data.currentSOC || [];
		if(length > 0){
			for(var i = 0; i < length; i++){
				if(outputVoltageData[i][0] > tempOutputVoltageData[tempOutputVoltageData.length - 1][0]){
					tempOutputVoltageData.push(outputVoltageData[i]);
					tempOutputElectricData.push(outputElectricData[i]);
					tempCurrentSOCData.push(currentSOCData[i]);
				}
			}
		}
		outputVoltageData = tempOutputVoltageData;
		outputElectricData = tempOutputElectricData;
		currentSOCData = tempCurrentSOCData;
	}
	setTimeout(function (){chargingChart.hideLoading();}, 200);
	startEchart = true;
	changeEchart();
}
function searchEquipmentStatus(data){
	equipmentStatusData = data && data.equipmentStatus || {};
	if (!equipmentStatusData) {
		if (!$("#detailID", parent.document).val()) {
			$('#errorInfo').html("无法查看监控内容，充电桩号为空！");
		} else {
			$('#errorInfo').html("无法查看监控内容，请确认充电桩号：" + $("#detailID", parent.document).val() + "是否存在或者可被监控！");
		}
	}
	allTable(data);
	if (equipmentStatusData && equipmentStatusData.communicationState == "正常") {
		time = 4000;
	} else {
		time = 8000;
	}
//	if (equipmentStatusData && equipmentStatusData.chargingStationName) {
//		$("#chargingStationName").html('<a class="details" onclick=\'chargingStationName("0")\'>' + equipmentStatusData.chargingStationName + '</a>');
//	}
	setTimeout(search, time);
}
function chargingStationName(num){
	window.parent.detalisDrop('chargingStation/chargingStationDetail', num, $("#currentPage").val(), "drownDown1", "" ,"chargingStationPage" ,"chargingStation");
	$("#parentSkipMenu", parent.document).val("chargingStationPage");
}
function initSocStatusChart(){
	socStatusChart = echarts.init(document.getElementById('stationEcharts'));
	socStatusChart.setOption(setPieStatus("统计信息", [{value: 0, name: "0", "itemStyle": echartStyle('#EAEAEA', false, false, '#EAEAEA')}], ['75%', '80%'], "当前SOC", "0%", "{d}%"));
}
function allTable(data){
	if (!$("#detailOneBody").html()) {
		$("#chargingStationNameTitle").html(equipmentStatusData && equipmentStatusData.chargingStationName || '未获取到充电桩详细数据');
		createDetailUlBody("detailOneBody", equipmentRealTimeDetailTable, equipmentStatusData, 1);
	}
	if (chargingGun != (equipmentStatusData && equipmentStatusData.chargingGun)) {
		chargingGun =  (equipmentStatusData && equipmentStatusData.chargingGun);
		if (chargingGun == "已连接") {
			$("#chargingGun").html('<img style="height:30px;" src="static/images/linkPng.png"/>' + chargingGun);
		} else {
			$("#chargingGun").html('<img style="height:30px;" src="static/images/noLinkPng.png"/>' + "未连接");
		} 
	}
	if (!$("#detailThreeBody").html()) {
		createDetailUlBody("detailThreeBody", equipmentRealTimeDetailTable, undefined, 3);
	}
	if (deviceState == undefined || (equipmentStatusData && equipmentStatusData.deviceState == "充电中")) {
		countData = [];
		countData.push({"value": floor(equipmentStatusData && equipmentStatusData.startSOC || 0, 0), 
			"name":floor(equipmentStatusData && equipmentStatusData.startSOC || 0, 0), 
			"itemStyle": echartStyle('#419AF1', false, false, '#419AF1')
			});
		countData.push({"value": (equipmentStatusData && (equipmentStatusData.currentSOC - equipmentStatusData.startSOC) || 0), 
			"name":(equipmentStatusData && (equipmentStatusData.currentSOC - equipmentStatusData.startSOC) || 0), 
			"itemStyle": echartStyle('#09BE09', false, false, '#09BE09')
			});
		countData.push({"value": (equipmentStatusData && (100 - (equipmentStatusData.currentSOC > 0 ? equipmentStatusData.currentSOC : 100)) || 0), 
			"name":(equipmentStatusData && (100 - (equipmentStatusData.currentSOC > 0 ? equipmentStatusData.currentSOC : 100)) || 0), 
			"itemStyle": echartStyle('#EAEAEA', false, false, '#EAEAEA')
			});
		option.series[0].data = countData;
		option.title.text = ((equipmentStatusData.currentSOC || 0) + "%");
		socStatusChart.setOption(option, true);
		$("#stationEcharts")[0].children[0].style.margin="auto";
		$("#stationEcharts")[0].children[0].style.width = $("#stationEcharts").width();
		$("#startSOC").html(floor(equipmentStatusData && equipmentStatusData.startSOC || 0, 0) + "%");
		$("#totalSOC").html((equipmentStatusData && (equipmentStatusData.currentSOC - equipmentStatusData.startSOC) || 0)+ "%");
		$("#chargedKWH").html(equipmentStatusData && equipmentStatusData.chargedKWH || 0);
		
		$("#outputVoltage").html((equipmentStatusData && equipmentStatusData.outputVoltage || 0));
		var outputVoltageValue = floor((equipmentStatusData && equipmentStatusData.outputVoltage || 0) / 750, 2) * 100;
		scrollMsg("outputVoltageValue", outputVoltageValue);
		$("#outputVoltageProgress").css({width: outputVoltageValue + "%"});
	//	$("#outputVoltage").html(floor(equipmentStatusData.outputVoltage / 750, 2) * 100 + "%");
		
		$("#outputElectric").html((equipmentStatusData && equipmentStatusData.outputElectric || 0));
		var outputElectricValue = floor((equipmentStatusData && equipmentStatusData.outputElectric || 0) / 600, 2);
		scrollMsg("outputElectricValue", outputElectricValue);
		$("#outputElectricProgress").css({width: outputElectricValue * 100 + "%"});
	//	$("#outputElectric").html(floor(equipmentStatusData.outputElectric / 600, 2) * 100 + "%");
		
		$("#outputPower").html((equipmentStatusData && equipmentStatusData.outputPower || 0));
		var outputPowerValue = floor((equipmentStatusData && equipmentStatusData.outputPower || 0) / 450, 2);
		scrollMsg("outputPowerValue", outputPowerValue);
		$("#outputPowerProgress").css({width: outputPowerValue * 100 + "%"});
	//	$("#outputPower").html(floor(equipmentStatusData.outputPower / 450, 2) * 100 + "%");
		
		//*****
		$("#carNumber").html(equipmentStatusData && equipmentStatusData.carNumber || "-");
		$("#carNo").html(equipmentStatusData && equipmentStatusData.carNo || "-");
		$("#cardNo").html(equipmentStatusData && equipmentStatusData.cardNo || "-");
		//*****
		
		if(deviceState == "充电中" && (outputVoltageData.length == 0 || (outputVoltageData.length > 0 && outputVoltageData[outputVoltageData.length -1][0] < data.requestDTTM))){
			var outputVoltage = [];
			var outputElectric = [];
			var currentSOC = [];
			var date = timeStamp2String(getSystemTime().getTime());
			outputVoltage.push(data && data.requestDTTM || date);
			outputVoltage.push(equipmentStatusData && equipmentStatusData.outputVoltage || 0);
			outputElectric.push(data && data.requestDTTM || date);
			outputElectric.push(equipmentStatusData && equipmentStatusData.outputElectric || 0);
			currentSOC.push(data && data.requestDTTM || date);
			currentSOC.push(equipmentStatusData && equipmentStatusData.currentSOC || 0);
			outputVoltageData.push(outputVoltage);
			outputElectricData.push(outputElectric);
			currentSOCData.push(currentSOC);
			if (startEchart) {
				if (equipmentStatusData && equipmentStatusData.chargedTime) {
					$("#chargedTime").html(equipmentStatusData && equipmentStatusData.chargedTime || '-');
				} else {
					$("#chargedTime").html(formatTime((stringToDate(outputVoltageData[0][0]) - stringToDate(data && data.requestDTTM || date)) / 1000));
				}
				changeEchart();
			}
			outputVoltage = [];
			outputElectric = [];
			currentSOC = [];
			date = undefined;
		}
	} else {
		if (startEchart) {
			outputVoltageData = [];
			outputElectricData = [];
		}
	}
	
	if (deviceState != (equipmentStatusData && equipmentStatusData.deviceState)) {
		deviceState = equipmentStatusData && equipmentStatusData.deviceState;
		if (deviceState == "充电中") {
			$("#deviceState").html('<img style="height:50px;" src="static/images/equipmentCharging.png"/>' + deviceState);
		} else if (deviceState == "充电结束") {
			$("#deviceState").html('<img style="height:50px;" src="static/images/equipmentCharged.png"/>' + deviceState);
			return;
		} else if (deviceState == "空闲") {
			$("#deviceState").html('<img style="height:50px;" src="static/images/equipmentIdle.png"/>' + deviceState);
		} else if (deviceState == "故障") {
			$("#deviceState").html('<img style="height:50px;" src="static/images/equipmentFault.png"/>' + deviceState);
		} else {
			$("#deviceState").html('<img style="height:50px;" src="static/images/equipmentOffline.png"/>' + "断开");
		}
//		$("#carNumber").html(equipmentStatusData && equipmentStatusData.carNumber || "-");
//		$("#carNo").html(equipmentStatusData && equipmentStatusData.carNo || "-");
//		$("#cardNo").html(equipmentStatusData && equipmentStatusData.cardNo || "-");
	}
//	if (deviceState != "充电中") {
//		outputVoltageData = [];
//		outputElectricData = [];
//		changeEchart();
//	}
}
function scrollMsg(scrollValue, scrollStyle){
	$("#" + scrollValue)[0].style.cssText="text-align:left;"
	if (scrollStyle > 60) {
		$("#" + scrollValue)[0].style.paddingLeft = 0 + "px";
		$("#" + scrollValue)[0].style.cssText="text-align:right;"
	} else if (scrollStyle > 20) {
		$("#" + scrollValue)[0].style.paddingLeft = (scrollStyle - 15) + "%";
	} else {
		$("#" + scrollValue)[0].style.paddingLeft = 0 + "px";
	} 
}
function changeEchart(){
    var option = {
            tooltip : {
            	trigger: 'axis',
//            	formatter: 'value'
            	axisPointer:{
            		label: {
            			formatter: function (params) {
            				if (params && params.value) {
            					return timeStamp2String(new Date(params.value)).substr(11);
            				} else {
            					'时间异常';
            				}
            			}
            		}
            	}
            },
            legend: {
            	x: 'right',
                data:['充电电压','充电电流','充电SOC']
            },
            dataZoom: {
                show: true
            },
            xAxis: [
                {
                	type: 'time',
                	name: '充电时间',
                	min: (outputVoltageData && outputVoltageData[0] && outputVoltageData[0][0]) || '',
                	max: (outputVoltageData && outputVoltageData[outputVoltageData.length - 1] && outputVoltageData[outputVoltageData.length - 1][0]) || '',
                	splitNumber: (outputVoltageData && outputVoltageData.length && outputVoltageData.length) < 10 ? outputVoltageData && outputVoltageData.length : 10,
                	axisLabel: {
                		formatter : function (chargingTime) {
                			if(chargingTime){
                				return timeStamp2String(new Date(chargingTime)).substr(11);
                			} else {
                				return '';
                			}
                        }
                	}
                }
            ],
            yAxis: [
                {
                    type: 'value',
                    name: '充电电压',
                	min: 0,
                	max: 750,
                    position: 'left',
                    axisLine: {
                        lineStyle: {
                            color: '#01b2ac',
                        }
                    },
                    axisLabel: {
                        formatter: '{value}'
                    }
                },
                {
                    type: 'value',
                    name: '充电电流',
                    min: 0,
                    max: 750,
                    position: 'right',
                    axisLine: {
                        lineStyle: {
                            color: '#09be09',
                        }
                    },
                    axisLabel: {
                        formatter: '{value}'
                    }
                },
                {
                    type: 'value',
                    name: '充电SOC',
                    min: 0,
                    max: 100,
                    position: 'right',
                    show: false,
                    axisLine: {
                        lineStyle: {
                            color: '#fe902f',
                        }
                    },
                    axisLabel: {
                        formatter: '{value}'
                    }
                }
            ],
            series: [
                {
                    name:'充电电压',
                    type:'line',
                    symbol:'none',
                    itemStyle: {
                        normal : {
                            color: '#01b2ac',
                        }
                    },
                    data:outputVoltageData
                },
                {
                    name:'充电电流',
                    type:'line',
                    symbol:'none',
                    yAxisIndex:1,
                    itemStyle: {
                        normal : {
                            color: '#09be09',
                        }
                    },
                    data:outputElectricData
                },
                {
                    name:'充电SOC',
                    type:'line',
                    symbol:'none',
                    yAxisIndex:2,
                    itemStyle: {
                        normal : {
                            color: '#fe902f',
//                            lineStyle: { 
//                            	width: 0
//                            }
                        }
                    },
                    data:currentSOCData
                }
            ]
        };
    chargingChart.setOption(option);
}
function goback() {
	if ($("#parentSkipMenu", parent.document).val() == "chargingStationPage") {
		$("#detailID", parent.document).val(equipmentStatusData && equipmentStatusData.chargingStationID);
		window.parent.skipMenu('chargingStation/chargingStationRealTimeDetail', 'drownDown1', '', 'chargingStationPage', 'chargingStationStatus');
	} else if ($("#parentSkipMenu", parent.document).val() == "equipmentPage") {
		window.parent.skipMenu('chargingEquipment/equipmentRealTimeStatus', 'drownDown2', '', 'equipmentPage', 'equipmentRealTimeStatus');
	}
}
